package com.ihrm.modules.sys.controller;

import com.ihrm.common.exception.RRException;
import com.ihrm.common.utils.IdWorker;
import com.ihrm.common.utils.PageUtils;
import com.ihrm.common.utils.R;
import com.ihrm.modules.sys.entity.RoleEntity;
import com.ihrm.modules.sys.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 
 * @author gaogzhen
 * @email gaogzhen@foxmail.com
 * @date 2020-12-17 20:56:33
 */
@RestController
@RequestMapping("sys/role")
@Api(tags = "Role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @Autowired
    private IdWorker idWorker;

    /**
     * 列表
     */
    @GetMapping
    @ApiOperation("列表")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = roleService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @GetMapping("/{id}")
    @ApiOperation("根据ID查询")
    public R info(@PathVariable("id") Long id) {
        RoleEntity role = roleService.getById(id);

        return R.ok().put("role", role);
    }

    /**
     * 保存
     */
    @PostMapping
    @ApiOperation("添加")
    public R save(@RequestBody RoleEntity role) {
        roleService.save(role);

        return R.ok();
    }

    /**
     * 修改
     */
    @PutMapping
    @ApiOperation("修改")
    public R update(@RequestBody RoleEntity role) {
        // ValidatorUtils.validateEntity(role);
        roleService.updateById(role);

        return R.ok();
    }

    /**
     * 删除
     */
    @DeleteMapping
    @ApiOperation("删除")
    public R delete(@RequestBody Long[] ids) {
        roleService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    @PostMapping("/assignPerms")
    @ApiOperation("分配权限")
    public R assignPerms(@RequestBody Map<String, Object> map) {
        if (ObjectUtils.isEmpty(map) || !map.containsKey("id") || !map.containsKey("permIds")) {
            throw new RRException("角色或者权限不能为空");
        }
        roleService.assignPerms(map);
        return R.ok();
    }

    @GetMapping("/all")
    @ApiOperation("获取所有的角色")
    public R all(String companyId) {
        List<RoleEntity> roles = roleService.all(companyId);
        return R.ok().put("roles", roles);
    }
}
